# -*- coding:utf-8 -*-

from flask import Flask,jsonify,make_response
from flask.ext import restful
from  apiService.errorCode import ErrorCode
from apiService.resources.webResources.getMysqlGroupAndInstance import getMysqlGroups
from apiService.resources.agentResources.slowLogAgentApi import SlowLogHandler
import logging
import json
from apiService.errorCode import CustomFlaskErr
from util.Logger import Logger
logger = Logger('apiServer.log',logging.DEBUG,logging.DEBUG)

errorCode= ErrorCode()

def output_json(data, code, headers=None):
    """Makes a Flask response with a JSON encoded body"""
    resp = make_response(json.dumps(data), code)
    resp.headers.extend(headers or {})

    return resp

class Api(restful.Api):
    def __init__(self, *args, **kwargs):
        super(Api, self).__init__(*args, **kwargs)
        self.representations = {
            'application/json': output_json,
        }




app = Flask(__name__)

@app.errorhandler(CustomFlaskErr)
def handle_flask_error(error):

    # response 的 json 内容为自定义错误代码和错误信息
    response = jsonify(error.to_dict())

    # response 返回 error 发生时定义的标准错误代码
    response.status_code = error.status_code

    return response


api = Api(app)
app.config.update(RESTFUL_JSON=dict(ensure_ascii=False))
api.add_resource(getMysqlGroups, '/web/mysqlGroupList')
api.add_resource(SlowLogHandler, '/agent/getSlowConf')

""""MYSQL_NOT_EXISTS_IN_MANAGE_LIST = 700001  # MYSQL 不在管理列表中
J_MSG = {MYSQL_NOT_EXISTS_IN_MANAGE_LIST: 'MYSQL_NOT_EXISTS_IN_MANAGE_LIST'}

class CustomFlaskErr(Exception):

    # 默认的返回码
    status_code = 400

    # 自己定义了一个 return_code，作为更细颗粒度的错误代码
    def __init__(self, return_code=None, status_code=None, payload=None):
        Exception.__init__(self)
        self.return_code = return_code
        if status_code is not None:
            self.status_code = status_code
        self.payload = payload

    # 构造要返回的错误代码和错误信息的 dict
    def to_dict(self):
        rv = dict(self.payload or ())

        # 增加 dict key: return code
        rv['return_code'] = self.return_code

        # 增加 dict key: message, 具体内容由常量定义文件中通过 return_code 转化而来
        rv['message'] = J_MSG[self.return_code]

        # 日志打印
        logger.warning(J_MSG[self.return_code])

        return rv


@app.errorhandler(CustomFlaskErr)
def handle_flask_error(error):

    # response 的 json 内容为自定义错误代码和错误信息
    response = jsonify(error.to_dict())

    # response 返回 error 发生时定义的标准错误代码
    response.status_code = error.status_code

    return response

"""
if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5001)
